import { useEffect, useState } from "react";
import { Card, Space, Input, Button, Table, Switch, Modal, Form } from "antd";
import {
  PlusOutlined,
  AppstoreTwoTone,
  EditTwoTone,
  DeleteTwoTone,
  ZoomInOutlined,
  RedoOutlined,
} from "@ant-design/icons";
import { UserFz } from "../../stores/UserFz";
import { RoleFz } from "../../stores/RoleFz";
import { useSnapshot } from "valtio";

export default function RoleManagement() {
  const userFz = useSnapshot(UserFz);
  const roleFz = useSnapshot(RoleFz);
  useEffect(() => {
    roleFz.getRoleList();
    userFz.getUserList();
  }, []);
  const copyData = {
    username: "",
    password: "",
    phone: "",
    email: "",
    brand: "",
    region: "",
    shop: "",
    role: "",
    status: true,
  };
  const change = (select:any,data:any) => {
    console.log(select,data)
    let updateData = {
      _id: data._id,
      status: select,
    };
    userFz.updateUserList(updateData)
    userFz.getUserList()
  }
  const [data, setData] = useState({
    username: "",
    password: "",
    phone: "",
    email: "",
    brand: "",
    region: "",
    shop: "",
    role: "",
    status: true,
  });
  const [tro, setTro] = useState(true);
  let [id, setID] = useState("");
  const AddList = async () => {
    userFz.addUserList(data);
    userFz.getUserList();
    setOpen(false);
  };
  const handleEditClick = (record: any) => {
    setData(record);
  };
  const EditList = () => {
    let updateData = {
      _id: id,
      ...data,
    };
    userFz.updateUserList(updateData);
    setOpen(false);
    userFz.getUserList();
  };
  const arr = roleFz.data;
  const [open, setOpen] = useState(false);
  const maskPassword = (password: string) => {
    if (!password) return "";
    const firstChar = password.charAt(0);
    const lastChar = password.charAt(password.length - 1);
    const maskedPart = "*".repeat(password.length - 2);
    return `${firstChar}${maskedPart}${lastChar}`;
  };
  const dataSource = userFz.data;
  const columns = [
    {
      title: "序号",
      dataIndex: "_id",
      key: "_id",
    },
    {
      title: "用户姓名",
      dataIndex: "username",
      key: "_id",
    },
    {
      title: "登录账号",
      dataIndex: "phone",
      key: "_id",
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "_id",
      render: (password: string) => maskPassword(password),
    },
    {
      title: "所属品牌",
      dataIndex: "brand",
      key: "_id",
      render: (brand: string) => (!brand ? "-" : brand),
    },
    {
      title: "所属大区",
      dataIndex: "region",
      key: "_id",
      render: (region: string) => (!region ? "-" : region),
    },
    {
      title: "所属店铺",
      dataIndex: "shop",
      key: "_id",
      render: (shop: string) => (!shop ? "-" : shop),
    },
    {
      title: "角色类型",
      dataIndex: "roleName",
      key: "_id",
    },
    {
      title: "启用",
      dataIndex: "status",
      key: "_id",
      render: (text: any,record:any) => <Switch id={text} checked={record.status} onChange={(e) => change(e,record)} />,
    },
    {
      title: "操作",
      key: "_id",
      render: (text: any) => (
        <Space>
          <Button
            type="link"
            onClick={() => {
              setTro(false);
              setOpen(true);
              handleEditClick(text);
              setID(text._id);
            }}
          >
            <EditTwoTone />
            编辑
          </Button>
          <Button type="link">
            <AppstoreTwoTone />
            冻结
          </Button>
          <Button type="link">
            <DeleteTwoTone />
            删除
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <div className="mt-10">
      <Card title="数据筛选" className="w-[90%] m-auto">
        <div>
          <Space className="mr-10">
            请输入查询：
            <Input
              placeholder="姓名/账号"
              size="large"
              className="mr-20"
              value={userFz.name}
              onChange={(e) => {
                userFz.xgname(e.target.value);
              }}
            />
          </Space>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                userFz.getUserList();
              }}
            >
              <ZoomInOutlined />
              查询
            </Button>
            <Button type="dashed">
              {" "}
              <RedoOutlined />
              重置
            </Button>
          </Space>
        </div>
      </Card>
      <Card
        title="角色列表"
        className="mt-10 w-[90%] m-auto"
        extra={
          <Button
            type="primary"
            onClick={() => {
              setOpen(true);
              setTro(true);
            }}
          >
            <PlusOutlined />
            添加
          </Button>
        }
      >
        <Table dataSource={dataSource} columns={columns} />;
      </Card>
      <Modal
        title="添加用户"
        centered
        open={open}
        footer={null}
        onCancel={() => setOpen(false)}
        width={700}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          style={{ width: 700, marginTop: 50 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item label="用户名称">
            <Input
              placeholder="请输入用户名称"
              onChange={(e) => {
                setData({ ...data, username: e.target.value });
              }}
              value={data.username}
            />
          </Form.Item>
          <Form.Item label="用户类型">
            {arr.map((item:{name:string}, index) => (
              <Button
                className="mr-2"
                key={index}
                type={item.name === data.role ? "primary" : "dashed"}
                onClick={() => {
                  setData({ ...data, role: item.name });
                }}
              >
                {item.name}
              </Button>
            ))}
          </Form.Item>
          <Form.Item label="用户账号">
            <Input
              placeholder="请输入用户账号"
              onChange={(e) => {
                setData({ ...data, phone: e.target.value });
              }}
              value={data.phone}
            />
          </Form.Item>
          <Form.Item label="用户密码">
            <Input.Password
              placeholder="请输入用户密码"
              onChange={(e) => {
                setData({ ...data, password: e.target.value });
              }}
              value={data.password}
            />
          </Form.Item>
          <Form.Item label="所属品牌">
            <Input
              placeholder="请输入所属品牌"
              value={data.brand}
              onChange={(e) => {
                setData({ ...data, brand: e.target.value });
              }}
            />
          </Form.Item>
          <Form.Item label="所属大区">
            <Input
              placeholder="请输入所属大区"
              onChange={(e) => {
                setData({ ...data, region: e.target.value });
              }}
              value={data.region}
            />
          </Form.Item>
          <Form.Item label="所属店铺">
            <Input
              placeholder="请输入所属店铺"
              value={data.shop}
              onChange={(e) => {
                setData({ ...data, shop: e.target.value });
              }}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button
              className={`${tro ? "" : "hidden"}`}
              type="primary"
              onClick={() => {
                AddList();
              }}
            >
              确认添加
            </Button>
            <Button
              className={`${tro ? "hidden" : ""}`}
              type="primary"
              onClick={() => {
                EditList();
              }}
            >
              确认修改
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setOpen(false);
                setData(copyData);
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
